package fr.cohen.factory;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.Properties;

import javax.swing.Icon;
import javax.swing.ImageIcon;

import fr.cohen.exception.ImageException;
import fr.cohen.image.CohenImage;
import fr.cohen.image.ImageRepository;
import fr.cohen.image.simple.CohenImageIcon;

public class ImageFactory {

	private static Properties factories = null;
	private static ImageFactory instance = null;

	protected ImageFactory() throws ImageException{

		factories = new Properties();
		InputStream stream = this.getClass().getResourceAsStream("factory.properties");
		try {
			factories.load(stream);
			stream.close();
		}
		catch (IOException e) {
			throw new ImageException(e);
		}
		stream = null;
	}

	public static ImageFactory getFactory() throws ImageException{

		if(instance == null){
			instance = new ImageFactory();
		}
		return instance;
	}

	@SuppressWarnings("unchecked")
	protected Object create(String key) throws ImageException{

		try{
			Object instance = null;
			String className = factories.getProperty(key);

			Class classe = Class.forName(className);

			try {

				Method method = classe.getMethod("getInstance", new Class[]{});
				instance = method.invoke(null, new Object[]{});
				method = null;
			}
			catch (Exception exception) {

				instance = classe.newInstance();
			}

			classe = null;
			className = null;

			return instance;
		}
		catch(Exception e){

			throw new ImageException(e);
		}
	}

	public ImageRepository createRepositoryImageProxy() throws ImageException{

		return (ImageRepository)create("fr.cohen.repository.proxy");
	}

	public ImageRepository createRepositoryImage() throws ImageException{

		return (ImageRepository)create("fr.cohen.repository.simple");
	}

	public CohenImage createImage(String name, Icon icon) throws ImageException{

		return new CohenImageIcon(name, (ImageIcon)icon);
	}
}
